package com.capinfo.accumulation.web.controller.collection;

import com.capinfo.accumulation.model.collection.Company;
import com.capinfo.accumulation.model.collection.CompanyHistory;
import com.capinfo.accumulation.parameter.collection.CompanyHistoryParameter;
import com.capinfo.accumulation.parameter.collection.CompanyParameter;
import com.capinfo.accumulation.service.collection.CompanyHistoryService;
import com.capinfo.commons.project.model.security.SystemUser;
import com.capinfo.commons.project.utils.JsonUtils;
import com.capinfo.framework.service.CommonsDataOperationService;
import com.capinfo.framework.util.IOUtils;
import com.capinfo.framework.util.LogUtils;
import com.capinfo.framework.web.Constants;
import com.capinfo.framework.web.controller.CommonsDataManageController;
import com.capinfo.framework.web.util.ControllerUtils;
import com.capinfo.framework.web.util.WebRequestUtils;
import com.capinfo.framework.web.view.model.DataListViewModel;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @Comment 单位信息历史表
 * <p>
 * Created by Rexxxar on 2017/9/27.
 */
@Controller
@RequestMapping("/business/collection/company_history")
public class CompanyHistoryController extends CommonsDataManageController<CompanyHistoryParameter, CompanyHistory> {

    private static final Log logger = LogFactory.getLog(CompanyHistory.class);

    @Autowired
    private CompanyHistoryService companyHistoryService;

    /**
     * 数据确认 保存
     *
     * @Author: Rexxxar
     * @Description
     * @Date: 2017/9/28 10:32
     */
    @RequestMapping("/history/save_or_update.shtml")
    public void saveOrUpdate(NativeWebRequest request, CompanyHistoryParameter companyHistoryParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);


        JSONObject jsonObject = new JSONObject();

        SystemUser user = (SystemUser) WebRequestUtils.retrieveSessionAttribute(request, Constants.ADMIN_ATTRIBUTE_KEY);

        try {
            companyHistoryParameter.getEntity().setOperatorId(user.getId());
            companyHistoryParameter.getCompanyAccount().setOperatorId(user.getId());
            companyHistoryService.saveOrUpdate(companyHistoryParameter);
            jsonObject.put("id", companyHistoryParameter.getEntity().getId());
            jsonObject.put("creditCode", companyHistoryParameter.getEntity().getGbOrganizationCode());
            jsonObject.put("result", "true");

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }

    }


    @Override
    public CommonsDataOperationService<CompanyHistory, CompanyHistoryParameter> getCommonsDataOperationService() {

        return companyHistoryService;
    }

    //在历史表中查询网点变更数据
    //fjs
    @RequestMapping("/site_list.shtml")
    public ModelAndView index(NativeWebRequest request, CompanyParameter parameter) {
        CompanyHistoryParameter hisParameter = new CompanyHistoryParameter();
        Company fromCompany = parameter.getEntity();
        CompanyHistory toHisCompany = new CompanyHistory();
        fromCompany.setGbCompanyAccount(parameter.getGbCompanyAccount());
        BeanUtils.copyProperties(fromCompany, toHisCompany, new String[]{"id", "companyId", "gbCompanyName", "gbOrganizationCode", "creditCode", "competentCode", "natureAccountId", "natureAccount", "companyInsideClassification",
                "organizationTypeId", "organizationType", "gbCompanyEconomicType", "companyEconomicTypeId", "companyEconomicType", "gbCompanyIndustries", "companyIndustriesId",
                "companyIndustries", "gbCompanyRelationships", "companyRelatoinships", "gbCompanyAddress", "registeredAddress", "registeredPostCode",
                "gbCompanyPostCode", "gbCompanyEmail", "gbCompanyCreationDate", "companyAddress", "legalPersonality", "gbLegalPersonIdCardType", "legalPersonIdCardTypeId", "legalPersonIdCardType",
                "gbLegalPersonName", "gbLegalPersonIdCardNumber", "legalPersonMobilePhone", "companyOpenedDate", "gbCompanyPayDay", "gbAgentName",
                "gbAgentIdCardType", "agentIdCardTypeId", "agentIdCardType", "gbAgentIdCardNumber", "gbAgentMobilePhone", "gbAgentTelephone", "gbTrusteeBank",
                "gbTrusteeBankCode", "delegationBranch", "delegationBranchCode", "paymentSite", "regionId", "region", "contactMobilePhone",
                "contactName", "contactIdCardNumber", "contactIdCardTypeId", "contactIdCardType", "contactAddress", "unitCode", "restDay",
                "responCode", "newFlag", "custNo", "manageState", "payDay", "dateTime", "operatorId", "SystemUseroperator", "bankCode", "siteId", "confirmerId",
                "confirmer", "confirmationTime", "channels", "createName", "companyHistoryId",});

        hisParameter.setEntity(toHisCompany);

        Map<String, Object> viewModel = ControllerUtils.buildViewModel();

        if (listBeforeInvoke(request, hisParameter)) {

            List<CompanyHistory> entities = new ArrayList<CompanyHistory>();

            long totalCount = getCommonsDataOperationService().getTotalCount(hisParameter);

            if (0 != totalCount) {

                entities = companyHistoryService.getList(hisParameter, totalCount, hisParameter.getCurrentPieceNum());

            }

            viewModel.putAll(new DataListViewModel<CompanyHistory>(hisParameter.getEntityClazz().getSimpleName() + "List", entities, totalCount, getCommonsDataOperationService(), hisParameter).buildViewModel());
        }
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/business/collection/company/site_list");
        mav.addAllObjects(viewModel);
        return mav;
    }

    //网点更改确认保存到历史表
    //fjs
    @RequestMapping("/history/save_change_site.shtml")
    public String saveChangesite(NativeWebRequest request, CompanyHistoryParameter companyHistoryParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        List list = new ArrayList();

        JSONObject jsonObject = new JSONObject();


        SystemUser user = (SystemUser) WebRequestUtils.retrieveSessionAttribute(request, Constants.ADMIN_ATTRIBUTE_KEY);


        try {
            //SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            companyHistoryParameter.getEntity().setConfirmationTime(new Date());
            companyHistoryParameter.getEntity().setOperatorId(user.getId());
            companyHistoryParameter.getCompanyAccount().setOperatorId(user.getId());
            CompanyHistory companyHistory = companyHistoryService.saveChangesite(companyHistoryParameter);

            jsonObject.put("result", "true");
            jsonObject.put("companyHistoryId", companyHistory.getId());

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }
        return  jsonObject.toString();
    }


    //在历史表中查询单位信息变更数据
    //fjs
    @RequestMapping("/company_info_list.shtml")
    public ModelAndView companyInfoList(NativeWebRequest request, CompanyParameter parameter) {
        CompanyHistoryParameter hisParameter = new CompanyHistoryParameter();
        /*Company fromCompany = parameter.getEntity();
        CompanyHistory toHisCompany = new CompanyHistory();
        fromCompany.setCompanyHistoryId(parameter.getCompanyHistoryId());
        BeanUtils.copyProperties(fromCompany, toHisCompany, new String[]{"id", "companyId", "gbCompanyName", "gbOrganizationCode", "creditCode", "competentCode", "natureAccountId", "natureAccount", "companyInsideClassification",
                "organizationTypeId", "organizationType", "gbCompanyEconomicType", "companyEconomicTypeId", "companyEconomicType", "gbCompanyIndustries", "companyIndustriesId",
                "companyIndustries", "gbCompanyRelationships", "companyRelatoinships", "gbCompanyAddress", "registeredAddress", "registeredPostCode",
                "gbCompanyPostCode", "gbCompanyEmail", "gbCompanyCreationDate", "companyAddress", "legalPersonality", "gbLegalPersonIdCardType", "legalPersonIdCardTypeId", "legalPersonIdCardType",
                "gbLegalPersonName", "gbLegalPersonIdCardNumber", "legalPersonMobilePhone", "companyOpenedDate", "gbCompanyPayDay", "gbAgentName",
                "gbAgentIdCardType", "agentIdCardTypeId", "agentIdCardType", "gbAgentIdCardNumber", "gbAgentMobilePhone", "gbAgentTelephone", "gbTrusteeBank",
                "gbTrusteeBankCode", "delegationBranch", "delegationBranchCode", "paymentSite", "regionId", "region", "contactMobilePhone",
                "contactName", "contactIdCardNumber", "contactIdCardTypeId", "contactIdCardType", "contactAddress", "unitCode", "restDay",
                "responCode", "newFlag", "custNo", "manageState", "payDay", "dateTime", "operatorId", "SystemUseroperator", "bankCode", "siteId", "confirmerId",
                "confirmer", "confirmationTime", "channels", "createName", "gbCompanyAccount"});*/

        hisParameter.getEntity().setId(parameter.getCompanyHistoryId());

        Map<String, Object> viewModel = ControllerUtils.buildViewModel();

        if (listBeforeInvoke(request, hisParameter)) {

            List<CompanyHistory> entities = new ArrayList<CompanyHistory>();

            long totalCount = getCommonsDataOperationService().getTotalCount(hisParameter);

            if (0 != totalCount ) {

                entities = companyHistoryService.getCompanyInfoChangeList(hisParameter, totalCount, hisParameter.getCurrentPieceNum());

            }

            viewModel.putAll(new DataListViewModel<CompanyHistory>(hisParameter.getEntityClazz().getSimpleName() + "List", entities, totalCount, getCommonsDataOperationService(), hisParameter).buildViewModel());
        }
        ModelAndView mav = new ModelAndView();
        mav.setViewName("/business/collection/company_info_change/list");
        mav.addAllObjects(viewModel);
        return mav;
    }


    //单位信息更改确认保存到历史表
    //fjs
    @RequestMapping("/save_basic_info_change.shtml")
    public String saveBasicInfoChange(NativeWebRequest request, CompanyParameter companyParameter, OutputStream stream) {

        WebRequestUtils.setCharacterEncodingForUTF8(request);
        WebRequestUtils.setContentTypeForHTML(request);
        List list = new ArrayList();

        JSONObject jsonObject = new JSONObject();


        SystemUser user = (SystemUser) WebRequestUtils.retrieveSessionAttribute(request, Constants.ADMIN_ATTRIBUTE_KEY);

        try {

            CompanyHistoryParameter companyHistoryParameter=new CompanyHistoryParameter();
            //赋值
            companyHistoryParameter.getEntity().setGbCompanyName(companyParameter.getEntity().getGbCompanyName());
            companyHistoryParameter.getEntity().setCompetentCode(companyParameter.getEntity().getCompetentCode());
            companyHistoryParameter.getEntity().setCompanyAddress(companyParameter.getEntity().getCompanyAddress());
            companyHistoryParameter.getEntity().setCompanyRelatoinships(companyParameter.getEntity().getCompanyRelatoinshipsId());
            companyHistoryParameter.getEntity().setCompanyEconomicTypeId(companyParameter.getEntity().getCompanyEconomicTypeId());
            companyHistoryParameter.getEntity().setLegalPersonality(companyParameter.getEntity().getLegalPersonality());
            companyHistoryParameter.getEntity().setGbLegalPersonName(companyParameter.getEntity().getGbLegalPersonName());
            companyHistoryParameter.getEntity().setGbLegalPersonName(companyParameter.getEntity().getGbLegalPersonName());
            companyHistoryParameter.getEntity().setLegalPersonIdCardTypeId(companyParameter.getEntity().getLegalPersonIdCardTypeId());
            companyHistoryParameter.getEntity().setLegalPersonMobilePhone(companyParameter.getEntity().getLegalPersonMobilePhone());
            companyHistoryParameter.getEntity().setContactName(companyParameter.getEntity().getContactName());
            companyHistoryParameter.getEntity().setContactIdCardTypeId(companyParameter.getEntity().getContactIdCardTypeId());
            companyHistoryParameter.getEntity().setContactIdCardNumber(companyParameter.getEntity().getContactIdCardNumber());
            companyHistoryParameter.getEntity().setContactMobilePhone(companyParameter.getEntity().getContactMobilePhone());
            //确认时间
            companyHistoryParameter.getEntity().setConfirmationTime(new Date());
            //操作员
            companyHistoryParameter.getEntity().setOperatorId(user.getId());
            //历史Id（参数）
            companyHistoryParameter.setCompanyHistoryId(companyParameter.getEntity().getCompanyHistoryId());
            CompanyHistory companyHistory = companyHistoryService.saveBasicInfoChange(companyHistoryParameter);

            jsonObject.put("result", "true");
            jsonObject.put("entity.companyHistoryId", companyHistory.getId());

        } catch (Exception e) {

            jsonObject.put("result", "false");
            LogUtils.debugException(logger, e);
        }

        try {

            IOUtils.outputByStream(stream, jsonObject.toString().getBytes("UTF-8"));

        } catch (UnsupportedEncodingException e) {

            LogUtils.debugException(logger, e);
        }
        return  jsonObject.toString();
    }
}
